from concurrent.futures import ThreadPoolExecutor,Future
from public_way import public_invoking
from utils.times_tool.time_control import now_time
from multiprocessing import Process, Queue
from utils.mysqlUtils.db_utils import DB
from utils.noticeUtils.dingtalkControl import DingTalkSendMsg
from utils.logging_tool.log_control import ERROR1, INFO1



class OnsaleReportUpdate:

    """
    根据在售报告更新冷库数据
    """

    public_program = public_invoking()

    def data_comparison(self, data):

        ListingPrice = data["ListingPrice"]
        ASINorItemID = data["ASINorItemID"]
        OrderSourceSKU = data["OrderSourceSKU"]
        IsFBA = data["IsFBA"]
        IsOffShelf = data["IsOffShelf"]
        ListingSoldNum = data["ListingSoldNum"]
        # print(f"{data}开始验证")

        sql = f"SELECT COUNT(*) FROM aml_amazon_product_base_dep86 " \
              f"WHERE OrderSourceID = 5005 AND ListingPrice = {ListingPrice} AND OrderSourceSKU = '{OrderSourceSKU}' " \
              f"AND ASINorItemID = '{ASINorItemID}' AND IsFBA = {IsFBA} AND ListingSoldNum = {ListingSoldNum} AND IsOffShelf = {IsOffShelf};"

        cold_base = DB("mysql_db_code_base")
        cold_res = cold_base.execute_sql_many(sql)
        # print(cold_res)
        if cold_res[0]["COUNT(*)"] == 0:
            ERROR1.logger.error(f"{data}>>>>>>>>>存在异常")
        else:
            print(f"{data}>>>>>>>>>正常")

    def thread_pool_work(self, q):

        # 创建线程池
        pool = ThreadPoolExecutor()
        while not q.empty():
            try:
                except_json = q.get()
                pool.submit(self.data_comparison, except_json)
            except:
                continue
        pool.shutdown(True)

    def salereport_updata_colddb(self, ordersourceid, date):

        # 获取在售报告数据
        url = f"http://dataservice-hd.zhcxkj.com/amazon/reports?customerId=1&orderSourceId={ordersourceid}&date={date}"
        payload = ""
        res = public_invoking().requests_api("GET", url, payload)

        # 获取在售报告变更数据并推到队列
        insales_data = []
        for i in res["list"]:
            i["ListingPrice"] = float(i["price"])
            i["ASINorItemID"] = i["asin"]
            i["OrderSourceSKU"] = i["sku"]
            if i["quantity"] == '':
                i["IsFBA"] = 1
                i["IsOffShelf"] = 0
                i["ListingSoldNum"] = 0
            elif int(i["quantity"]) > 0:
                i["IsFBA"] = 0
                i["IsOffShelf"] = 0
                i["ListingSoldNum"] = int(i["quantity"])
            else:
                i["IsFBA"] = 0
                i["IsOffShelf"] = 2
                i["ListingSoldNum"] = int(i["quantity"])
            del i["price"], i["quantity"], i["asin"], i["sku"]
            insales_data.append(i)

        for i in insales_data:
            ListingPrice = i["ListingPrice"]
            ASINorItemID = i["ASINorItemID"]
            OrderSourceSKU = i["OrderSourceSKU"]
            IsFBA = i["IsFBA"]
            IsOffShelf = i["IsOffShelf"]
            ListingSoldNum = i["ListingSoldNum"]
            sql = f"SELECT COUNT(*) FROM aml_amazon_product_base_dep86 " \
                  f"WHERE OrderSourceID = 5005 AND ListingPrice = {ListingPrice} AND OrderSourceSKU = '{OrderSourceSKU}' " \
                  f"AND ASINorItemID = '{ASINorItemID}' AND IsFBA = {IsFBA} AND ListingSoldNum = {ListingSoldNum} AND IsOffShelf = {IsOffShelf};"
            cold_base = DB("mysql_db_code_base")
            cold_res = cold_base.execute_sql_many(sql)
            if cold_res[0]["COUNT(*)"] == 0:
                ERROR1.logger.error(f"{i}>>>>>>>>>存在异常")
            else:
                print(f"{i}>>>>>>>>>正常")

        # report = f"执行时间{now_time()}条    \n" \
        #          f"通过在售报告接口获取在售数据{len(insales_data)}条    \n" \
        #          f"服务通过在售报告更新数据{len(insales_data)}条    \n" \
        #          f"发现异常数据{len(err)}条 \n" \
        #          f"异常数据明细:  \n" \
        #          f"{err}"
        # return report


if __name__ == '__main__':
    ordersourceid = '5005'
    date = '2023-03-07'
    # sql = "SELECT IsOffShelf, ListingPrice, ASINorItemID, OrderSourceSKU, CONVERT(IsFBA, SIGNED )AS IsFBA, ListingSoldNum FROM aml_amazon_product_base_dep86 WHERE OrderSourceID = 5005 AND UpdateTime >= '2023-03-05';"
    res = OnsaleReportUpdate().salereport_updata_colddb(ordersourceid, date)
    print(res)
